/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-03-09     CGY       the first version
 */
#include "rtthread.h"
#include "rtdevice.h"
#include "board.h"
#include "pwm_out.h"

#define TIM2_BASE_FREQUENCY 100000000
#define PWM_PERIOD  ((TIM2_BASE_FREQUENCY / PWM_FREQUENCY / 2) - 1)

static void TIM2_PWM_Out_Init(uint16_t Prescaler, uint16_t Period, uint16_t Pulse)
{
    GPIO_InitTypeDef GPIO_Initstruct = {0};

    __HAL_RCC_GPIOA_CLK_ENABLE();
    GPIO_Initstruct.Pin         = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3;
    GPIO_Initstruct.Mode        = GPIO_MODE_AF_PP;
    GPIO_Initstruct.Pull        = GPIO_PULLUP;
    GPIO_Initstruct.Speed       = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_Initstruct.Alternate   = GPIO_AF1_TIM2;
    HAL_GPIO_Init(GPIOA, &GPIO_Initstruct);

    TIM_HandleTypeDef  TIM2_Handler = {0};
    TIM_OC_InitTypeDef TIM2_CH_Handler = {0};

    __HAL_RCC_TIM2_CLK_DISABLE();
    __HAL_RCC_TIM2_CLK_ENABLE();

    TIM2_Handler.Instance           = TIM2;
    TIM2_Handler.Init.Prescaler     = Prescaler;
    TIM2_Handler.Init.CounterMode   = TIM_COUNTERMODE_CENTERALIGNED1;
    TIM2_Handler.Init.Period        = Period;
    HAL_TIM_PWM_Init(&TIM2_Handler);

    TIM2_CH_Handler.OCMode=TIM_OCMODE_PWM1;
    TIM2_CH_Handler.Pulse= Pulse;
    TIM2_CH_Handler.OCPolarity=TIM_OCPOLARITY_HIGH;

//    HAL_TIM_PWM_ConfigChannel(&TIM2_Handler,&TIM2_CH_Handler,TIM_CHANNEL_1);//配置TIM2通道1
    HAL_TIM_PWM_ConfigChannel(&TIM2_Handler,&TIM2_CH_Handler,TIM_CHANNEL_2);//配置TIM2通道2
    HAL_TIM_PWM_ConfigChannel(&TIM2_Handler,&TIM2_CH_Handler,TIM_CHANNEL_3);//配置TIM2通道3
    HAL_TIM_PWM_ConfigChannel(&TIM2_Handler,&TIM2_CH_Handler,TIM_CHANNEL_4);//配置TIM2通道4

//    HAL_TIM_PWM_Start(&TIM2_Handler,TIM_CHANNEL_1);//开启PWM通道1
    HAL_TIM_PWM_Start(&TIM2_Handler,TIM_CHANNEL_2);//开启PWM通道2
    HAL_TIM_PWM_Start(&TIM2_Handler,TIM_CHANNEL_3);//开启PWM通道3
    HAL_TIM_PWM_Start(&TIM2_Handler,TIM_CHANNEL_4);//开启PWM通道4
}


#if 1
void Set_pwm(unsigned short int* pwm)
{
//    TIM2->CCR1 = pwm[0];
    TIM2->CCR2 = pwm[0];
    TIM2->CCR3 = pwm[1];
    TIM2->CCR4 = pwm[2];
}
#endif

static int pwm_out_init(void)
{
    TIM2_PWM_Out_Init(0, PWM_PERIOD, PWM_PERIOD / 2);

    return RT_EOK;
}

/* 导出到自动初始化 */
INIT_BOARD_EXPORT(pwm_out_init);
